import util from '@/common/util.js'
import appConfig from '@/common/config/config.js'
import storage from '@/common/unistorage/index.js'


let api = {
	domain: appConfig.domain
}

const getToken = async () => {
	let token = storage.getToken();
	if (token) {
		return token;
	} else {
		const userInfo = getApp().globalData.userInfo;
		if(!userInfo){
			
			getApp().globalData.VuePrototype.$cw.goLoginHome();
			return;
		}
		uni.showLoading({
			title: '处理中...',
			mask: false,
		});
		let data = getApp().globalData.VuePrototype.$cw.jsEncrypt({
			userGUID: userInfo.id,
			openid: userInfo.openid,
			wxUserInfoMobilePhone: userInfo.wxUserInfoMobilePhone||null
		});
		let res = await uni.request({
			method: 'POST',
			url: api.domain + '/api/services/app/TokenAuthService/CreateWxAccessToken',
			data: data
		});
		uni.hideLoading();
		if (res) {
			res.data = getApp().globalData.VuePrototype.$cw.jsDecrypt(res.data);
			if (res.data.success) {
				let token = `Bearer ${res.data.result.accessToken}`;
				storage.setToken(`Bearer ${res.data.result.accessToken}`, res.data.result.expireInSeconds);
				return token;
			} else {
				 getApp().globalData.VuePrototype.$cw.goLoginHome();
			}
		} else {
			 getApp().globalData.VuePrototype.$cw.goLoginHome();
		}
	}
};

const Request = async (option) => {
	const userInfo=getApp().globalData.userInfo;
	const lastApiDomain = option.url.startsWith('http') ? '' : api.domain;
	if (!option.isObj) {
		// 假如只有一个参数就拼接到url上（EFcore单个参数只能这么传递）
		let paramData = util.urlEncode(option.data);
		// isObj参数为假，则把option.data参数写入url
		option.url = lastApiDomain + option.url + '?' + paramData;
		option.data = '';
	} else {
		// isObj参数为真，data 放到post里面去传递
		option.url = lastApiDomain + option.url;
		if(option.data&&userInfo&&!option.data.userInfoGUID){
			option.data.userInfoGUID = userInfo.id;
		}
	}
	if (option.isEncrypt&&option.data) {
		option.oldData=getApp().globalData.VuePrototype.$util.deepCopy(option.data);
		option.data = getApp().globalData.VuePrototype.$cw.jsEncrypt(option.data);
	}

	option.header = {
		'X-Requested-With': 'XMLHttpRequest',
	};

	// 需要token 才请求
	if (!option.isNotNeedToken) {
		if(userInfo&&userInfo.id){
			option.header.Authorization = await getToken();
		}else{
			return null;
		}
	}

	// 需要传入wx.request()的method属性，默认设置为'post'
	if (option.method != 'GET') {
		option.method = 'POST';
	}
	if (option.isShowLoading) {
		appConfig.REQUESTAPICOUNT++; // 非静默加载那么需要把请求数加一
		uni.showLoading({
			title: '处理中...',
			mask: false,
		});
	}

	let errorMsg = '';
	try {
		let rdata = await uni.request(option);
		if (option.isEncrypt) {
			rdata.data = getApp().globalData.VuePrototype.$cw.jsDecrypt(rdata.data);
			
			// 解密处理 三次重试
			for(let retryCount=0;retryCount<3;retryCount++){
				if(!rdata.data.success&&rdata.data.error.message.includes('解密失败')){
					option.data = getApp().globalData.VuePrototype.$cw.jsEncrypt(option.oldData);
					rdata = await uni.request(option);
					rdata.data = getApp().globalData.VuePrototype.$cw.jsDecrypt(rdata.data);
				}
			}
		}
		
		if (rdata && (rdata.data.success === true || rdata.data.success === undefined)) {
			option.abpSuccess && option.abpSuccess(rdata.data.result);
		} else if (rdata && !rdata.data.success) {
			if (rdata.data.error.message) {
				errorMsg = rdata.data.error.message;
			}
			if (rdata.data.error.validationErrors) {
				rdata.data.error.validationErrors.forEach(item => {
					errorMsg += item.message + ',';
				});
				errorMsg = errorMsg.substring(0, errorMsg.length - 1);
			}
		
			option.abpFail && option.abpFail();
		}

		// 防止hideLoading 把showToast 展示出来隐藏掉
		if (errorMsg) {
			errorMsg = errorMsg.indexOf("服务器内部") != -1 ? '系统繁忙,请稍后再试' : errorMsg;
			uni.showToast({
				title: '提示信息 : ' + errorMsg,
				icon: 'none',
				duration: option.duration || 3000
			});

			// 有错误信息就返回空
			return null;
		}

		let result = rdata.data == 'null' ? null : rdata.data;

		if (rdata.data.hasOwnProperty('result')) {
			result = rdata.data.result || {};
		}

		if (result) {
			result = util.null2str(result);
		}

		return result;
	} finally {
		if (option.isShowLoading) {
			appConfig.REQUESTAPICOUNT--; // 非静默加载那么需要把请求数加一
		}

		if (appConfig.REQUESTAPICOUNT <= 0) {
			uni.hideLoading();
		}
	}
}

export default {
	Request
};